import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy
import ch.qos.logback.core.status.OnConsoleStatusListener

statusListener(OnConsoleStatusListener)

def props = new Properties()
props.load(this.getClass().getClassLoader().getResourceAsStream("config/application.properties"))

def config = new ConfigSlurper().parse(props)

def env = System.getProperty('profile.env') ?: 'production'
def appenderList = []
def level = ERROR
def LOG_DIR = config.log.basePath + '/' + config.app.name

if (env == 'production' || env == 'regressiontest') {
    appenderList.add("ROLLING")
    level = INFO
} else {
    appenderList.add("CONSOLE")
    appenderList.add("ROLLING")
    level = INFO
}

if (env == 'development') {
    appender("CONSOLE", ConsoleAppender) {
        encoder(PatternLayoutEncoder) { pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" }
    }
}

if (env == 'production' || env == 'regressiontest') {
    appender("ROLLING", RollingFileAppender) {
        encoder(PatternLayoutEncoder) { Pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" }
        rollingPolicy(TimeBasedRollingPolicy) {
            fileNamePattern = "${LOG_DIR}/application.%d{yyyy-MM-dd_HH}.log"
            triggeringPolicy(timeBasedFileNamingAndTriggeringPolicy) { maxFileSize = '1024M' }
        }
    }
}

if (env == 'development') {
    logger("com.ibatis", DEBUG, ["CONSOLE"])
    logger("com.ibatis.common.jdbc.SimpleDataSource", DEBUG, ["CONSOLE"])
    logger("com.ibatis.common.jdbc.ScriptRunner", DEBUG, ["CONSOLE"])
    logger("com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate", DEBUG, ["CONSOLE"])
    logger("java.sql.Connection", DEBUG, ["CONSOLE"])
    logger("java.sql.Statement", DEBUG, ["CONSOLE"])
    logger("java.sql.PreparedStatement", DEBUG, ["CONSOLE"])

}

root(level, appenderList)